package mviewer.renderer.jogl.drawer;

import com.jogamp.opengl.util.texture.Texture;
import java.util.Map;
import javax.media.opengl.GL2;
import mviewer.types.IPolygon;
import mviewer.types.ITexturedPolygon;
import mviewer.types.IVertex;
import mviewer.types.Material;
import mviewer.types.SegregatedDataIterator;
import mviewer.types.TextureCoordinate;

public class FixedTextureCoordinateDrawer extends ColoredPolygonDrawer {

	protected Map<Material, Texture> textures;

	public FixedTextureCoordinateDrawer(GL2 gl, Map<Material, Texture> textures) {
		super(gl);
		this.textures = textures;
	}

	@Override
	public void draw(SegregatedDataIterator<IPolygon> polygons, Material material) {
		Texture texture = textures.get(material);

		if (texture == null) {
			super.draw(polygons, material);
			return;
		}

		gl.glTexEnvi(GL2.GL_TEXTURE_ENV, GL2.GL_TEXTURE_ENV_MODE, GL2.GL_REPLACE);
		gl.glTexParameteri(GL2.GL_TEXTURE_2D, GL2.GL_TEXTURE_GEN_MODE, GL2.GL_NONE);
		applyMaterial(material);
		texture.enable();
		texture.bind();

		while (polygons.hasNext())
			drawPolygon(polygons.next().getTexturedPolygon());

		texture.disable();
	}

	private void drawPolygon(ITexturedPolygon polygon) {
		IVertex[]			v = polygon.getVertices();
		TextureCoordinate[] t = polygon.getTextureCoordinates();

		gl.glBegin(GL2.GL_POLYGON);

		for (int i = 0; i < v.length; i++) {
			gl.glTexCoord2f(t[i].getU(), t[i].getV());
			drawVertex(gl, v[i]);
		}

		gl.glEnd();
	}
}
